package util;

import com.google.common.collect.Lists;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @Desciption:
 * @author: Jacky Chai
 * @date: 2019/5/8
 */
public class AncCollectionUtil {

    /**
     * 分批次处理
     *
     * @param list
     * @param threshold
     * @param consumer
     * @param <E>
     */
    public static <E> void partitionConsume(List<E> list, int threshold, Consumer<List<E>> consumer) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        Assert.isTrue(threshold > 0, "阀值必须大于0");
        Assert.notNull(consumer, "consumer不能为空");
        List<List<E>> subList = Lists.partition(list, threshold);
        for (List<E> item : subList) {
            consumer.accept(item);
        }
    }


    /**
     * 自定义list去重
     * @param list 需要去重的对象
     * @param distinctKeyGenerator 去重逻辑接口 (apply 参数为列表项，返回值为去重的key对象)
     * @return 参数list中元素去重后的新列表
     * */
    public static <T,K> List<T> customListDistinct(List<T> list, Function<T,K> distinctKeyGenerator){
        HashMap<K,T> distinctMap = new HashMap<>();
        for(T item : list){
            K key = distinctKeyGenerator.apply(item);
            distinctMap.putIfAbsent(key, item);
        }

        return new ArrayList<>(distinctMap.values());
    }
}
